package me.aartikov.sharedelementanimationsample.slice;

import me.aartikov.alligator.NavigationContext;
import me.aartikov.alligator.NavigationContextBinder;
import me.aartikov.alligator.Navigator;
import me.aartikov.alligator.helpers.FractionStack;
import me.aartikov.alligator.screenswitchers.FragmentScreenSwitcher;
import me.aartikov.alligator.Screen;
import me.aartikov.sharedelementanimationsample.ResourceTable;
import me.aartikov.sharedelementanimationsample.SampleApplication;
import me.aartikov.sharedelementanimationsample.SampleTransitionAnimationProvider;
import me.aartikov.sharedelementanimationsample.screens.FirstScreen;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.ability.fraction.FractionAbility;
import ohos.aafwk.content.Intent;

import java.util.List;

public class MainAbilitySlice extends AbilitySlice {
    private Navigator mNavigator = SampleApplication.getNavigator();
    private NavigationContextBinder mNavigationContextBinder = SampleApplication.getNavigationContextBinder();
    private FragmentScreenSwitcher mScreenSwitcher;

    private void bindNavigationContext() {
        NavigationContext.Builder builder = new NavigationContext.Builder(getAbility(), SampleApplication.getNavigationFactory())
                .screenSwitcher(mScreenSwitcher)
                .transitionAnimationProvider(new SampleTransitionAnimationProvider())
                .fragmentNavigation(((FractionAbility) getAbility()).getFractionManager());  // Use child fragment manager for nested navigation
        mNavigationContextBinder.bind(builder.build());
    }

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_main);
        mScreenSwitcher = new FragmentScreenSwitcher(SampleApplication.getNavigationFactory(), ((FractionAbility) getAbility()).getFractionManager());
    }

    private void setInitialFragmentIfRequired() {
        List<Screen> screens = FractionStack.getInstance(((FractionAbility) getAbility()).getFractionManager()).getCurrentFragmentScreen(getAbility().toString());
        if (screens.size() == 0 && mNavigator.canExecuteCommandImmediately()) {
            mNavigator.reset(new FirstScreen(ResourceTable.Id_fragment_container, getAbility().toString()));
        } else {
            mNavigator.reduce(screens);
        }
    }

    @Override
    public void onActive() {
        super.onActive();
        bindNavigationContext();
        setInitialFragmentIfRequired();
    }

    @Override
    public void onForeground(Intent intent) {
        super.onForeground(intent);
    }

    @Override
    public void onBackPressed() {
        mNavigator.goBack();
    }
}
